package com.personal.config.datasource;

import com.personal.common.constant.DataSourceConstant;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Ivos_Mgmt数据源配置
 */
@Configuration
@MapperScan(basePackages = "com.personal.dao.mgmt",sqlSessionTemplateRef = "mgmtSqlSessionTemplate")
public class MgmtDataSourceConfig {

    /**
     * 数据源
     * @return
     */
    @Bean(name = "mgmtDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mgmt")
    public DataSource mgmtDataSource(){
        return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
    }

    /**
     * SqlSessionFactory
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "mgmtSqlSessionFactory")
    public SqlSessionFactory authSqlSessionFactory(@Qualifier("mgmtDataSource") DataSource dataSource)throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(DataSourceConstant.IVOS_MGMT_MAPPER));
        return bean.getObject();
    }

    /**
     * 事务管理器
     * @param dataSource
     * @return
     */
    @Bean(name = "mgmtTransactionManager")
    public DataSourceTransactionManager authTransactionManager(@Qualifier("mgmtDataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * SqlSessionTemplate
     * @param sqlSessionFactory
     * @return
     * @throws Exception
     */
    @Bean(name = "mgmtSqlSessionTemplate")
    public SqlSessionTemplate authSqlSessionTemplate(@Qualifier("mgmtSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
